﻿using System;
using System.Data;
using System.Drawing;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Controls;
using DevExpress.XtraPrinting;
using Model;

namespace TaxiDispatchClient
{
    /// <summary>
    /// 驾驶员信息form
    /// </summary>
    public partial class DriverForm : XtraForm
    {
        /// <summary>
        /// 保存旧工号用于工号修改保存时更新
        /// </summary>
        private string _oldWorkId;      
        private string _phoneNumber;
        private Thread _thread;
        private bool _isAdd;
       
        public DriverForm()
        {
            InitializeComponent();             
        }

        private void DriverForm_Load(object sender, EventArgs e)
        {
            btn_select.Enabled = false;
            _thread = new Thread(BindData);
            _thread.IsBackground = true;
            _thread.Start();
        }        

        private  void BindData()
        {
            try
            {
                StringBuilder strWhere = new StringBuilder();
                //string para = string.Empty;
                //switch (radioGroup1.SelectedIndex)
                //{
                //    case 0:
                //        para = "taxino";
                //        break;
                //    case 1:
                //        para = "name";
                //        break;
                //    case 2:
                //        para = "phoneNumber";
                //        break;
                //}                
                //string paraValue = textEdit1.Text.Trim();
                //DataSet dsDriver = new DataSet();
                //if (paraValue == "")
                //{
                //    dsDriver = MainForm.PositionService.DriverGetList("");
                //}
                //else
                //{
                //    dsDriver = MainForm.PositionService.DriverGetListWithPar(para, paraValue);
                //}

                if (textEdit1.Text.Trim()!="")
                {
                    strWhere.Append(radioGroup1.Properties.Items[
                        radioGroup1.SelectedIndex].Value);
                    strWhere.Append(" like '%");
                    strWhere.Append(textEdit1.Text);
                    strWhere.Append("%' ");
                    if (MainForm.MyUserInfo.CompanyName!=Service.PowerConfig.MainCompanyName)
                    {
                        strWhere.Append("and CompanyName='");
                        strWhere.Append(MainForm.MyUserInfo.CompanyName);
                        strWhere.Append("'");
                    }
                }
                else
                {
                    if (MainForm.MyUserInfo.CompanyName != Service.PowerConfig.MainCompanyName)
                    {
                        strWhere.Append(" CompanyName like '");
                        strWhere.Append(MainForm.MyUserInfo.CompanyName);
                        strWhere.Append("%'");
                    }
                }
                DataSet dsDriver = MainForm.PositionService.DriverGetList(strWhere.ToString());
            
                BeginInvoke(new MethodInvoker(() =>
                { 
                    if(dsDriver!=null)
                   {
                        gridControl1.DataSource = dsDriver.Tables[0];
                        gridView1.GroupPanelText = "出租车司机列表-共" 
                            + dsDriver.Tables[0].Rows.Count+"位";
                        if (_isAdd)
                        {
                            gridView1.FocusedRowHandle = gridView1.RowCount - 1;
                            _isAdd = false;
                        }
                        gridView1_RowClick(null, null);
                        btn_select.Enabled = true;
                   }
                    
                }));
                     
            }
            catch (Exception ex)
            {               
               Common.CommonRoutine.HandlingExceptions(ex);
               btn_select.Enabled = true;                        
            }            
        }

        
       

        /// <summary>
        /// 新增按钮单击事件
        /// </summary>
        /// <param name="sender">sender</param>
        /// <param name="e">e</param>
        private void spBtn_Add_Click(object sender, EventArgs e)
        {
            if (btn_add.Tag.ToString() == "新增")
            {
                btnEdt_TaxiNo.Enabled = true;
                txtEdt_Name.Enabled = true;
                imgCmbEdt_Gender.Enabled = true;
                txtEdt_PhoneNumber.Enabled = true;
                textEdit_Imei.Enabled = true;
                txtEdt_WorkId.Enabled = true;
                textEdit_remark.Enabled = true;
                btn_select.Enabled = false;

                btnEdt_TaxiNo.Text = string.Empty;
                txtEdt_Name.Text = string.Empty;
                txtEdt_PhoneNumber.Text = string.Empty;
                textEdit_Imei.Text = string.Empty;
                txtEdt_WorkId.Text = string.Empty;
                textEdit_remark.Text = string.Empty;


                gridControl1.Enabled = false;
                btn_delete.Enabled = true;
                btn_modify.Enabled = false;
                btn_add.Image = Properties.Resources.UserForm_btnsave001;
                btn_add.Tag = "保存";
                btn_delete.Image = Properties.Resources.UserForm_btncancel001;
                btn_delete.Tag = "取消";
            }
            else
            {
                if (!CheckInput())
                {
                    return;
                }
                
                string driverName = txtEdt_Name.Text.Trim();
                ImageComboBoxItem imageComboBoxItem = imgCmbEdt_Gender.SelectedItem as ImageComboBoxItem;
                string Gender = imageComboBoxItem.Value.ToString();
                string PhoneNumber = txtEdt_PhoneNumber.Text.Trim();
                string WorkId = txtEdt_WorkId.Text.Trim();
                string Remark = textEdit_remark.Text.Trim();
                string imei = textEdit_Imei.Text.Trim();

                DriverInfo driverInfo = new DriverInfo();
                
                driverInfo.Name = driverName;
                driverInfo.Gender = Gender;
                driverInfo.PhoneNumber = PhoneNumber;
                driverInfo.IMEI = imei;
                driverInfo.WorkId = WorkId;
                driverInfo.Remark = Remark;
                driverInfo.TaxiID = Convert.ToInt32(btnEdt_TaxiNo.Tag);

                try
                {
                    if(MainForm.PositionService.DriverExistphone(PhoneNumber))
                    {
                        XtraMessageBox.Show("该手机号码已有司机使用，请核对！");
                        txtEdt_PhoneNumber.Focus();
                        return;
                    }
                    //if(MainForm.PositionService.DriverExist(WorkId))
                    //{
                    //    XtraMessageBox.Show("该工号已使用，请核对！");
                    //    txtEdt_WorkId.Focus();
                    //    return;
                    //}
                    if (MainForm.PositionService.DriverAdd(driverInfo))
                    {
                        XtraMessageBox.Show("新增成功");
                       
                        btnEdt_TaxiNo.Enabled = false;
                        txtEdt_Name.Enabled = false;
                        imgCmbEdt_Gender.Enabled = false;
                        txtEdt_PhoneNumber.Enabled = false;
                        textEdit_Imei.Enabled = false;
                        txtEdt_WorkId.Enabled = false;
                        textEdit_remark.Enabled = false;

                        gridControl1.Enabled = true;
                        btn_delete.Enabled = true;
                        btn_add.Enabled = true;
                        btn_modify.Enabled = true;
                        btn_add.Image = Properties.Resources.UserForm_btnadd001;
                        btn_add.Tag = "新增";
                        btn_delete.Image = Properties.Resources.UserForm_btndel001;
                        btn_delete.Tag = "删除";
                        btn_select.Enabled = true;
                        //DataSet dsDriver = MainForm.PositionService.DriverGetList(string.Empty);
                        //gridControl1.DataSource = dsDriver.Tables[0];
                        //gridView1.FocusedRowHandle = gridView1.RowCount - 1;
                        _isAdd = true;
                        _thread = new Thread(BindData);
                        _thread.Start();
                    }
                    else
                    {
                        XtraMessageBox.Show("新增失败");
                    }
                }
                catch (Exception ex)
                {
                    Common.CommonRoutine.HandlingExceptions(ex, true);
                }
            }
        }

        /// <summary>
        /// 修改按钮单击事件
        /// </summary>
        /// <param name="sender">sender</param>
        /// <param name="e">e</param>
        private void spBtn_Modify_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtEdt_Name.Text.Trim()))
            {
                XtraMessageBox.Show("请选择要修改的驾驶员信息！");
                return;
            }

            if (btn_modify.Tag.ToString() == "修改")
            {
                _oldWorkId = txtEdt_WorkId.Text.Trim();
                _phoneNumber = txtEdt_PhoneNumber.Text;
                btnEdt_TaxiNo.Enabled = true;
                txtEdt_Name.Enabled = true;
                imgCmbEdt_Gender.Enabled = true;
                txtEdt_PhoneNumber.Enabled = true;
                textEdit_Imei.Enabled = true;
                txtEdt_WorkId.Enabled = true;
                textEdit_remark.Enabled = true;
                btn_select.Enabled = false;

                gridControl1.Enabled = false;
                btn_delete.Enabled = true;
                btn_add.Enabled = false;
                btn_modify.Image = Properties.Resources.UserForm_btnsave001;
                btn_modify.Tag = "保存";
                btn_delete.Image = Properties.Resources.UserForm_btncancel001;
                btn_delete.Tag = "取消";
            }
            else
            {
                if (!CheckInput())
                {
                    return;
                }

                string driverName = txtEdt_Name.Text.Trim();
                ImageComboBoxItem imageComboBoxItem = imgCmbEdt_Gender.SelectedItem as ImageComboBoxItem;
                string Gender = imageComboBoxItem.Value.ToString();
                string PhoneNumber = txtEdt_PhoneNumber.Text.Trim();
                string WorkId = txtEdt_WorkId.Text.Trim();
                string imei = textEdit_Imei.Text.Trim();
                if (_phoneNumber != PhoneNumber)
                {
                    try
                    {
                        if (MainForm.PositionService.DriverExistphone(PhoneNumber))
                        {
                            XtraMessageBox.Show("该手机号码已有司机使用，请核对！");
                            txtEdt_PhoneNumber.Focus();
                            return;
                        }
                    }
                    catch (Exception ex)
                    {
                        Common.CommonRoutine.HandlingExceptions(ex, true);
                        return;
                    }
                }
                
                //if (WorkId != _oldWorkId)
                //{
                //    try
                //    {
                //        if (MainForm.PositionService.DriverExist(txtEdt_WorkId.Text.Trim()))
                //        {
                //            XtraMessageBox.Show("该驾驶员工号已使用，请重新输入");
                //            txtEdt_WorkId.Focus();
                //            return;
                //        }  
                //    }
                //    catch (Exception ex)
                //    {
                //        Common.CommonRoutine.HandlingExceptions(ex, true);
                //        return;
                //    }
                //}

                string Remark = textEdit_remark.Text.Trim();
                DataRow row = this.gridView1.GetDataRow(this.gridView1.FocusedRowHandle);
                int id = int.Parse(row["id"].ToString());
                             

                DriverInfo model = MainForm.PositionService.DriverGetModel(id);
                if(model == null)
                {
                    XtraMessageBox.Show("数据库中未找到该出租车，请重试！");
                    return;
                }
                model.Name = driverName;
                model.Gender = Gender;
                model.PhoneNumber = PhoneNumber;
                model.IMEI = imei;
                model.WorkId = WorkId;
                model.Remark = Remark;
                model.TaxiID = Convert.ToInt32(btnEdt_TaxiNo.Tag);

                try
                {
                    if (MainForm.PositionService.DriverUpdate(model))
                    {
                        XtraMessageBox.Show("修改成功");

                        btnEdt_TaxiNo.Enabled = false;
                        txtEdt_Name.Enabled = false;
                        imgCmbEdt_Gender.Enabled = false;
                        txtEdt_PhoneNumber.Enabled = false;
                        textEdit_Imei.Enabled = false;
                        txtEdt_WorkId.Enabled = false;
                        textEdit_remark.Enabled = false;

                        gridControl1.Enabled = true;
                        btn_delete.Enabled = true;
                        btn_add.Enabled = true;
                        btn_modify.Enabled = true;
                        btn_modify.Tag = "修改";
                        btn_modify.Image = Properties.Resources.UserForm_btnmodify001;
                        btn_delete.Tag ="删除";
                        btn_delete.Image = Properties.Resources.UserForm_btndel001;
                        btn_select.Enabled = true;
                        _thread = new Thread(BindData);
                        _thread.Start();
                    }
                    else
                    {
                        XtraMessageBox.Show("修改失败");
                    }
                }
                catch (Exception ex)
                {
                    Common.CommonRoutine.HandlingExceptions(ex, true);
                }
            }
        }

        /// <summary>
        /// 验证输入
        /// </summary>
        /// <returns>是否验证通过</returns>
        private bool CheckInput()
        {
            if (string.IsNullOrEmpty(btnEdt_TaxiNo.Text.Trim()))
            {
                XtraMessageBox.Show("请输入出租车牌号");
                btnEdt_TaxiNo.Focus();
                return false;
            }

            if (string.IsNullOrEmpty(txtEdt_Name.Text.Trim()))
            {
                XtraMessageBox.Show("请输入驾驶员姓名");
                txtEdt_Name.Focus();
                return false;
            }
            if (txtEdt_Name.Text.Length>30)
            {
                XtraMessageBox.Show("驾驶员姓名不能超过30字符");
                txtEdt_Name.Focus();
                return false;
            }

            if (string.IsNullOrEmpty(txtEdt_PhoneNumber.Text.Trim()))
            {
                XtraMessageBox.Show("请输入手机号");
                txtEdt_PhoneNumber.Focus();
                return false;
            }

            if(textEdit_Imei.Text.Length>15)
            {
                XtraMessageBox.Show("IMEI号码应不超过15位");
                textEdit_Imei.Focus();
                return false;
            }

            //if (string.IsNullOrEmpty(txtEdt_WorkId.Text.Trim()))
            //{
            //    XtraMessageBox.Show("请输入驾驶员工号");
            //    txtEdt_WorkId.Focus();
            //    return false;
            //}
            if (txtEdt_WorkId.Text.Trim().Length>20)
            {
                XtraMessageBox.Show("驾驶员工号过长");
                txtEdt_WorkId.Focus();
                return false;
            }

            return true;
        }

        /// <summary>
        /// grid行单击事件
        /// </summary>
        /// <param name="sender">sender</param>
        /// <param name="e">e</param>
        private void gridView1_RowClick(object sender, DevExpress.XtraGrid.Views.Grid.RowClickEventArgs e)
        {
            DataRow row = gridView1.GetDataRow(gridView1.FocusedRowHandle);
            if (row != null)
            {
                btnEdt_TaxiNo.Text = row["taxino"].ToString();
                btnEdt_TaxiNo.Tag = row["TaxiID"].ToString();
                txtEdt_Name.Text = row["Name"].ToString();
                txtEdt_PhoneNumber.Text = row["PhoneNumber"].ToString();
                textEdit_Imei.Text = row["IMEI"].ToString();
                txtEdt_WorkId.Text = row["WorkId"].ToString();
                string gender = row["Gender"].ToString();
                if (gender == "男")
                    imgCmbEdt_Gender.SelectedIndex = 0;
                else imgCmbEdt_Gender.SelectedIndex = 1;
                //ImageComboBoxItem imageComboBoxItem = new ImageComboBoxItem();
                //imageComboBoxItem.Value =                 
                textEdit_remark.Text = row["Remark"].ToString();
                btn_modify.Enabled = true;
            }
        }

        /// <summary>
        /// ...(选择出租车)按钮单击事件
        /// </summary>
        /// <param name="sender">sender</param>
        /// <param name="e">e</param>
        private void btnEdt_TaxiNo_ButtonClick(object sender, ButtonPressedEventArgs e)
        {
            TaxiInfoForm taxiInfoForm = new TaxiInfoForm();
            taxiInfoForm.ShowDialog();
            DataRow row = taxiInfoForm.gridView1.GetDataRow(taxiInfoForm.gridView1.FocusedRowHandle);
            if (row != null)
            {
                btnEdt_TaxiNo.Text = row["TaxiNo"].ToString();
                btnEdt_TaxiNo.Tag = row["id"];                
            }
        }

        /// <summary>
        /// 删除按钮单击事件
        /// </summary>
        /// <param name="sender">sender</param>
        /// <param name="e">e</param>
        private void spBtn_Del_Click(object sender, EventArgs e)
        {
            if (btn_delete.Tag.ToString()== "删除")
            {
                DataRow row = gridView1.GetDataRow(gridView1.FocusedRowHandle);
                if(row==null)
                {
                    XtraMessageBox.Show("请选择想要删除的司机信息");
                    return;
                }
                int id = int.Parse(row["id"].ToString());
                string taxino = row["taxino"].ToString();
                string drivername = row["Name"].ToString();
                if (XtraMessageBox.Show("您确实要删除牌照为【"+taxino+
                    "】,驾驶员姓名为【"+drivername+"】的这条信息？",
                    "删除驾驶员信息", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                  
                    try
                    {
                        if (MainForm.PositionService.DriverDelete(id))
                        {
                            XtraMessageBox.Show("删除成功！");
                            _thread = new Thread(BindData);
                            _thread.Start();
                        }
                    }
                    catch (Exception ex)
                    {
                        Common.CommonRoutine.HandlingExceptions(ex, true);
                    }
                }
            }
            else
            {
                btn_select.Enabled = true;
                btnEdt_TaxiNo.Enabled = false;
                txtEdt_Name.Enabled = false;
                imgCmbEdt_Gender.Enabled = false;
                txtEdt_PhoneNumber.Enabled = false;
                textEdit_Imei.Enabled = false;
                txtEdt_WorkId.Enabled = false;
                textEdit_remark.Enabled = false;

                gridView1_RowClick(null,null);
                gridControl1.Enabled = true;
                btn_delete.Enabled = true;
                btn_add.Enabled = true;
                btn_add.Tag = "新增";
                btn_add.Image = Properties.Resources.UserForm_btnadd001;
                btn_modify.Tag = "修改";
                btn_modify.Image = Properties.Resources.UserForm_btnmodify001;
                btn_delete.Tag = "删除";
                btn_delete.Image = Properties.Resources.UserForm_btndel001;
                btn_modify.Enabled = true;
            }
        }

        /// <summary>
        /// 查询按钮单击事件
        /// </summary>
        /// <param name="sender">sender</param>
        /// <param name="e">e</param>
        private void simpleButton_Select_Click(object sender, EventArgs e)
        {
            gridView1.GroupPanelText = "数据加载中...";
            btn_select.Enabled = false;
            _thread = new Thread(BindData);
            _thread.Start();
        }


        private void pictureEdit_exit_MouseHover(object sender, EventArgs e)
        {
            pictureBox1.Image = Properties.Resources.snedSmsexit;
            Cursor = Cursors.Hand;
        }

        private void pictureEdit_exit_MouseLeave(object sender, EventArgs e)
        {
            pictureBox1.Image = Properties.Resources.snedSmsexitPressDown;
            Cursor = Cursors.Arrow;
        }
        private void pictureBox1_Click(object sender, EventArgs e)
        {
            Close();
        }

        #region 窗体控件操作效果
        Point _mouseOff;
        bool _leftFlag;
        private void Form_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                _mouseOff = new Point(-e.X, -e.Y);
                _leftFlag = true;
            }
        }

        private void Form_MouseMove(object sender, MouseEventArgs e)
        {
            if (_leftFlag)
            {
                Point mouseSet = Control.MousePosition;
                mouseSet.Offset(_mouseOff.X, _mouseOff.Y);
                Location = mouseSet;
            }
        }

        private void Form_MouseUp(object sender, MouseEventArgs e)
        {
            if (_leftFlag)
            {
                _leftFlag = false;
            }
        }

        private void btn_MouseHover(object sender, EventArgs e)
        {
            Cursor = Cursors.Hand;
        }

        private void btn_MouseLeave(object sender, EventArgs e)
        {
            Cursor = Cursors.Arrow;
        }

        private void Form_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                Close();
            }
        }
       
#endregion
       
        private void btn_exportToExcel_Click(object sender, EventArgs e)
        {
            saveFileDialog1.FileName = "出租车司机列表";
            saveFileDialog1.Filter = "Excel文件(*.xls)|*.xls";
            if(saveFileDialog1.ShowDialog()== DialogResult.OK)
            {                
                gridView1.ExportToXls(saveFileDialog1.FileName);
                XtraMessageBox.Show("Excel导出完成！");     
            }

        }

        

        private void simpleButton1_Click(object sender, EventArgs e)
        {
            int count = 0;
            for (int i = 0; i < 10000; i++)
            {
                System.Threading.Thread.Sleep(10);
                string name = i.ToString();
                string gender = "男";
                string phoneNumber = i.ToString("00000000000");
                string workid = i.ToString();
                int taxiId = 18;
                string remark = "光通讯科技";
                DriverInfo driver = new DriverInfo
                {
                    Name = name,
                    Gender = gender,
                    PhoneNumber = phoneNumber,
                    WorkId = workid,
                    TaxiID = taxiId,
                    Remark = remark
                };
                if (MainForm.PositionService.DriverAdd(driver))
                    count++;

            }
            XtraMessageBox.Show(count.ToString());
        }

        private void DriverForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (_thread != null)
            {
                _thread.Abort();
            }
        }

        private void textEdit1_KeyPress(object sender, KeyPressEventArgs e)
        {            
            if ((Keys)e.KeyChar == Keys.Enter)
            {
                simpleButton_Select_Click(null, null);
            }     
        }
       
    }
}